<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 胖果果
 -->
<template>
  <div>
    <van-form class="fruit">
      <van-field
        v-model="ruleForm.userName"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onLogin">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>
  </div>
</template>

<script>
import { alertMsg, saveInfo, audio } from "@/utils/index";
import { JSEncrypt } from "jsencrypt";
export default {
  name: "Fruit",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      ruleForm: {
        userName: "17330553924",
        password: "Zz930329",
        errorCnt: 0
      },
      IntervalTime: 3,
      type: "0",
      startFlag: false,
      timer: null,
      returnContent: [],
      activeIndex: "",
      isAcceptSuc: false,
      token: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 47 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 47 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        // this.ruleForm.userName = this.item.user;
        // this.ruleForm.password = this.item.pass;
        // this.type = this.item.type || "0";
        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,
            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 47 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      //   this.ruleForm.userName = this.item.user;
      //   this.ruleForm.password = this.item.pass;
      //   this.type = this.item.type || "0";
    }
  },
  methods: {
    // 登录
    onLogin() {
      const _this = this;
      if (!this.startFlag) {
        this.returnContent = [];
        this.startFlag = true;
        this.returnContent.unshift(alertMsg("正在登录"));
        window.api.ajax(
          {
            url: "http://115.28.96.38:8081/user/pikeLogin",
            method: "post",
            returnAll: false,
            async: false,
            data: {
              values: this.ruleForm
            }
          },
          res => {
            if (res.success) {
              _this.returnContent.unshift(alertMsg("登录成功"));
              // 登录成功  => 保存账号信息
              saveInfo({
                user: _this.ruleForm.userName,
                pass: _this.ruleForm.password,
                type: _this.type,
                index: _this.index
              });
              _this.token = res.content.token;
              // 接单
              _this.onPickOrder(_this);
            } else {
              _this.returnContent.unshift(alertMsg(res.errorMessage));
              _this.startFlag = false;
            }
          }
        );
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 接单
    onPickOrder(_this) {
      clearInterval(_this.timer);
      window.api.ajax(
        {
          url: "http://115.28.96.38:8081/order/pickOrder1",
          method: "post",
          data: {
            values: _this.encryptedData("")
          },
          headers: {
            access_token: _this.token
          }
        },
        res => {
          if (res.success) {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          } else {
            _this.returnContent.unshift(alertMsg(res.errorMessage));
            _this.timer = setInterval(() => {
              _this.onPickOrder(_this);
            }, _this.IntervalTime * 1000);
          }
        }
      );
    },
    // 加密密码
    encryptedData(data) {
      //   var n = "-----BEGIN PUBLIC KEY-----\r\n";
      //   n += publicKey;
      //   n += "\r\n-----END PUBLIC KEY-----";
      // 新建JSEncrypt对象
      let encryptor = new JSEncrypt();
      // 设置公钥
      // 1443213098657129
      encryptor.setPublicKey("32fsfdi123neafba1b13e5f22961q2n2");
      // 加密数据
      return encryptor.encrypt(data);
    }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>